package com.manager.devicemanager.config;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.manager.devicemanager.common.DataSourceNameEnum;
import com.manager.devicemanager.entity.DeviceInfo;
import com.manager.devicemanager.entity.DeviceUser;
import com.manager.devicemanager.entity.Testbatch;
import com.manager.devicemanager.entity.UserInfo;
import com.manager.devicemanager.service.IDeviceInfoService;
import com.manager.devicemanager.service.IDeviceUserService;
import com.manager.devicemanager.service.ITestbatchService;
import com.manager.devicemanager.service.IUserInfoService;
import com.manager.devicemanager.util.SmsUtils;
import com.manager.devicemanager.util.YuYInSmsUtils;
import com.manager.devicemanager.vo.SmsParamVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.JmsListener;

import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Configuration
public class ActiveMQListener {

    private static final Logger logger = LoggerFactory.getLogger(ActiveMQListener.class);

    @Value("${mqtt.publish.topic1}")
    public String publishICTopic;
    @Value("${mqtt.publish.topic2}")
    public String publishIC2Topic;
    @Value("${mqtt.publish.topic3}")
    public String publishPDTopic;

    @Autowired
    private IDeviceInfoService iDeviceInfoService;
    @Autowired
    private IDeviceUserService iDeviceUserService;
    @Autowired
    private IUserInfoService iUserInfoService;
    @Autowired
    private ITestbatchService iTestbatchService;

    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private YuYInSmsUtils yuYInSmsUtils;

    // 提取公共处理报警消息的方法
    private void handleAlarmMessage(String mqttMessage, String topstart) {
        LambdaQueryWrapper<DeviceInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DeviceInfo::getTopic, topstart);
        DeviceInfo one = iDeviceInfoService.getOne(lambdaQueryWrapper);
        if (one != null) {
            LambdaQueryWrapper<DeviceUser> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(DeviceUser::getDeviceid, one.getId());
            List<DeviceUser> list = iDeviceUserService.list(lambdaQueryWrapper1);
            Set<String> stringStream = list.stream().map(DeviceUser::getUserid).collect(Collectors.toSet());
            LambdaQueryWrapper<UserInfo> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.in(UserInfo::getId, stringStream);
            List<UserInfo> list1 = iUserInfoService.list(lambdaQueryWrapper2);
//            JSONObject jsonObject = new JSONObject();
            JSONObject jsonObject1 = JSONObject.parseObject(mqttMessage, JSONObject.class);
            SmsParamVO smsParamVO=new SmsParamVO();
            smsParamVO.setMessage(jsonObject1.getString("Message"));
            smsParamVO.setTime(jsonObject1.getString("Time"));
            smsParamVO.setDevice_name(one.getName());
            if (list1.size() > 0){
                list1.forEach(item -> {
                     smsUtils.sendSms(item.getTel(), smsParamVO);

                    // 呼叫
                Boolean aBoolean = yuYInSmsUtils.sendPhone(item.getTel(), smsParamVO);
                if (aBoolean){
                    logger.info("呼叫成功");
                }else {
                    logger.error("呼叫失败");
                }
                });
            }

        }
        System.out.println("Received MQTT message: " + mqttMessage);
    }

    // 提取公共处理事件结果消息的方法
    private void handleEventResultMessage(String mqttMessage, String topstart) {
        JSONObject jsonObject = JSONObject.parseObject(mqttMessage, JSONObject.class);
        LambdaQueryWrapper<DeviceInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DeviceInfo::getTopic, topstart);
        DeviceInfo one = iDeviceInfoService.getOne(lambdaQueryWrapper);
        if (one != null) {
            String type = one.getType();
            String datasourceindex = one.getDatasourceindex();
            String eventresulttype = jsonObject.getString("type");
            String dataResourceName = "ic".equals(type) ? DataSourceNameEnum.ICBOARDCONFIG.getDataSourceName() + datasourceindex : DataSourceNameEnum.PDBOARDCONFIG.getDataSourceName() + datasourceindex;
            if ("开始成功".equals(eventresulttype)) {
                Testbatch testbatch = new Testbatch();
                testbatch.setBatchname(jsonObject.getString("batchname"));
                testbatch.setStarttime(Date.from(Instant.now()));
                iTestbatchService.updateTestBatchStartTime(dataResourceName, testbatch);
            } else if ("结束成功".equals(eventresulttype)) {
                Testbatch testbatch = new Testbatch();
                testbatch.setBatchname(jsonObject.getString("batchname"));
                testbatch.setEndtime(Date.from(Instant.now()));
                iTestbatchService.updateTestBatchEndTime(dataResourceName, testbatch);
            }
        }
        System.out.println("Received MQTT message: " + mqttMessage);
    }

    @JmsListener(destination = "${mqtt.publish.topic1}/alarm")
    public void ic1messageHandler(String mqttMessage) {
        handleAlarmMessage(mqttMessage, publishICTopic);
    }

    @JmsListener(destination = "${mqtt.publish.topic2}/alarm")
    public void ic2messageHandler(String mqttMessage) {
        handleAlarmMessage(mqttMessage, publishIC2Topic);
    }

    @JmsListener(destination = "${mqtt.publish.topic3}/alarm")
    public void pdmessageHandler(String mqttMessage) {
        handleAlarmMessage(mqttMessage, publishPDTopic);
    }

    @JmsListener(destination = "${mqtt.publish.topic1}/eventresult")
    public void mqttInputeventresultHandler1(String mqttMessage) {
        handleEventResultMessage(mqttMessage, publishICTopic);
    }

    @JmsListener(destination = "${mqtt.publish.topic2}/eventresult")
    public void mqttInputeventresultHandler2(String mqttMessage) {
        handleEventResultMessage(mqttMessage, publishIC2Topic);
    }

    @JmsListener(destination = "${mqtt.publish.topic3}/eventresult")
    public void mqttInputeventresultHandler3(String mqttMessage) {
        handleEventResultMessage(mqttMessage, publishPDTopic);
    }
}
